// 获得文章的分类数据，并放置于文章的下拉列表中
$.ajax({
  type: 'get',
  url: '/categories',
  success: function (response) {
    let html = template('categoryTpl', {
      data: response
    });
    $('#category').html(html);
  }
});

// 文章封面的上传
$('#feature').on('change', function () {
  let file = this.files[0];
  let formData = new FormData();
  formData.append('cover', file);
  $.ajax({
    type: 'post',
    url: '/upload',
    data: formData,
    // 告诉$.ajax方法不要处理data属性对应的参数
    processData: false,
    // 告诉$.ajax方法不要设置参数类型
    contentType: false,
    success: function (response) {
      console.log(response);
      $('#thumbnail').val(response[0].cover);
    }
  })
})

// 添加文章
$('#addForm').on('submit', function () {
  let formData = $(this).serialize();
  $.ajax({
    type: 'post',
    url: '/posts',
    data: formData,
    success: function () {
      location.href = '/admin/posts.html';
    }
  })
  return false;
})

// 从地址栏中获得查询参数
function getUrlParams(name) {
  let paramAry = location.search.substr(1).split('&');
  for (let i = 0; i < paramAry.length; i++) {
    let tmp = paramAry[i].split('=');
    if (tmp[0] == name) return tmp[1];
  }
  return null;
}

// 修改文章——显示原来的数据
if (getUrlParams('id') != null) {
  $.ajax({
    type: 'get',
    url: '/posts/' + getUrlParams('id'),
    success: function (response) {
      $.ajax({
        type: 'get',
        url: '/categories',
        success: function (categories) {
          response.categories = categories;
          console.log(response);
          let html = template('modifyTpl', response);
          $('#parentBox').html(html);
        }
      });
    }
  });
}

// 修改文章——提交
$('#parentBox').on('submit', '#modifyForm', function () {
  let formData = $(this).serialize();
  let id = $(this).attr('data-id');
  $.ajax({
    type: 'put',
    url: '/posts/' + id,
    data: formData,
    success: function () {
      location.href = '/admin/posts.html';
    }
  });
  return false;
})